using System;
using System.Collections.Generic;
using System.Text;
using AYO.Link.Log4Net;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;

namespace AYO.Link.SocketBase
{
    public class ClientHandler : SimpleChannelInboundHandler<IByteBuffer>
    {
        private readonly Action<string> _onTextReceived;

        public ClientHandler(Action<string> onTextReceived)
        {
            _onTextReceived = onTextReceived;
        }

        protected override void ChannelRead0(IChannelHandlerContext ctx, IByteBuffer msg)
        {
            var text = msg.ToString(Encoding.UTF8);
            _onTextReceived?.Invoke(text);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Log.Error($"Exception: {exception.Message}", exception);
            context.CloseAsync();
        }
    }
    
    public class Utf8Decoder : ByteToMessageDecoder
    {
        protected override void Decode(IChannelHandlerContext ctx, IByteBuffer input, List<object> output)
        {
            var length = input.ReadableBytes;
            if (length == 0)
            {
                return;
            }

            var bytes = new byte[length];
            input.ReadBytes(bytes);
            var text = Encoding.UTF8.GetString(bytes);
            output.Add(text);
        }
    }
}
